import os
from typing import Annotated
from uuid import uuid4

from fastapi import APIRouter, Depends, UploadFile, File
from sqlalchemy.orm import Session
from starlette.responses import JSONResponse

import models
from auth import get_current_active_user
from db import get_db
from models import official
from product.product_post import storage_path
from schemas import OfficialPublic

router = APIRouter(prefix="/api/official", tags=["官方"])

@router.get("/all")
def get_official_all(current_user: Annotated[models.User, Depends(get_current_active_user)],db: Session = Depends(get_db)):
    records=db.query(official).all()
    data_list=[]
    for record in records:
        item=OfficialPublic.from_orm(record)
        item.image=f"http://localhost:8000/{item.image}"
        data_list.append(item)
    return data_list


@router.post("/add")
async def add_product_with_image(name: str,description: str, image: UploadFile = File(None), db: Session = Depends(get_db)):
    unique_id = uuid4()
    if image:
        file_extension = os.path.splitext(image.filename)[1]
        unique_filename = f"{unique_id}{file_extension}"
        file_path = os.path.join(storage_path, unique_filename)
        with open(file_path, "wb") as buffer:
            buffer.write(await image.read())
        image_path = f"storage/product/{unique_filename}"
    else:
        image_path = None
    official = models.official(name=name, image=image_path, description=description)
    db.add(official)
    db.commit()
    db.refresh(official)
    data=OfficialPublic.from_orm(official)
    return JSONResponse(data)

